package com.tc.juc.pack06;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @Auther: tianchao
 * @Date: 2021/10/5 21:28
 * @Description:
 */
@Slf4j
public class Test36Stampe {
    static AtomicStampedReference<String> atomicReference = new AtomicStampedReference<>("A",0);

    public static void main(String[] args) {
        log.info("main start....");
        String prev = atomicReference.getReference();
        int stamp = atomicReference.getStamp();
        other();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("尝试 a -> c: {}", atomicReference.compareAndSet(prev, "C",stamp,stamp+1));
        log.info("修改后的值: {}", atomicReference.getReference());
    }

    private static void other() {
        new Thread(()->{
            int stamp = atomicReference.getStamp();
            log.info("版本号{}",stamp);
            log.info("尝试 a -> b: {}",atomicReference.compareAndSet(atomicReference.getReference(), "B",stamp,stamp+1));
        }).start();
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(()->{
            int stamp = atomicReference.getStamp();
            log.info("版本号{}",stamp);
            log.info("尝试 b -> a: {}",atomicReference.compareAndSet(atomicReference.getReference(), "A",stamp,stamp+1));
        }).start();
    }
}
